<template>
	<view class="consult-container">
		<!-- 顶部导航栏 -->
		<u-navbar :is-back="true" :title="shopName" title-color="#333" title-bold @leftClick="goToMyPage" placeholder>
			<view class="nav-right" slot="right" @click="showMenu">
				<u-icon name="more-dot-fill" size="40" color="#333"></u-icon>
			</view>
		</u-navbar>

		<!-- 宠物信息卡片 -->
		<view class="pet-card" v-if="petInfo">
			<image class="pet-image" :src="petInfo.image" mode="aspectFill"></image>
			<view class="pet-info">
				<text class="pet-name">{{ petInfo.title }}</text>
				<text class="pet-price">¥{{ petInfo.price }}</text>
			</view>
			<view class="pet-card-close" @click="closePetCard">
				<u-icon name="close" color="#999" size="24"></u-icon>
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<view class="chat-wrapper">
			<scroll-view class="chat-container" scroll-y="true" :scroll-top="scrollTop" 
				:scroll-with-animation="true" ref="chatScroll">
				<!-- 系统消息 -->
				<view class="system-message">
					<text>萌宠AI助手为您服务，复杂问题可联系人工客服</text>
				</view>
				
				<!-- 消息列表 -->
				<view class="message-list">
					<view class="message-date" v-if="messages.length > 0">
						<text>{{ formatDate(messages[0].time) }}</text>
					</view>

					<block v-for="(msg, index) in messages" :key="index">
						<!-- 日期分割线 -->
						<u-divider half-width="50%" v-if="index > 0 && shouldShowDate(messages[index - 1].time, msg.time)">
							{{ formatDate(msg.time) }}
						</u-divider>

						<view class="message-item" :class="{ 'message-self': msg.isSelf }">
							<u-avatar :src="msg.avatar" size="40" custom-style="background-color: #f0f0f0;"></u-avatar>
							<view class="message-wrapper">
								<view class="message-name" v-if="!msg.isSelf">
									<text>{{ shopName }}</text>
								</view>
								<view class="message-content" :class="{ 'image-message': msg.type === 'image' }">
									<!-- 文本消息 -->
									<rich-text class="message-text" v-if="msg.type !== 'image'"
										:nodes="formatMessage(msg.content)"></rich-text>

									<!-- 图片消息 -->
									<u-image v-if="msg.type === 'image'" :src="msg.content" mode="widthFix"
										class="message-image" @click="previewImage(msg.content)" width="400rpx"></u-image>
								</view>
								
								<!-- 消息状态和时间 -->
								<view class="message-footer">
									<view class="message-status" v-if="msg.isSelf && msg.status !== 'read'">
										<u-loading-icon v-if="msg.status === 'sending'" size="22" color="#ff6600"></u-loading-icon>
										<u-icon name="error-circle-fill" v-if="msg.status === 'failed'" color="#ff4d4f" size="22"></u-icon>
									</view>
									<text class="status-read" v-if="msg.isSelf && msg.status === 'read'">已读</text>
									<text class="message-time">{{ formatTime(msg.time) }}</text>
								</view>
							</view>
						</view>
					</block>
				</view>

				<!-- 正在输入提示 -->
				<view class="typing-indicator" v-if="isAiTyping">
					<view class="typing-dots">
						<view class="dot"></view>
						<view class="dot"></view>
						<view class="dot"></view>
					</view>
					<text>AI助手正在输入...</text>
				</view>
			</scroll-view>
		</view>

		<!-- 快捷回复 -->
		<view class="quick-reply-container" v-if="showQuickReply">
			<scroll-view class="quick-reply-scroll" scroll-x="true" :show-scrollbar="false">
				<view class="quick-reply-list">
					<view class="quick-reply-item" v-for="(item, index) in quickReplies" :key="index" @click="selectQuickReply(item)">
						{{ item }}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 底部输入区域 -->
		<view class="input-area">
			<view class="input-wrapper">
				<view class="input-box">
					<view class="input-tools">
						<u-icon class="tool-icon" name="photo" @click="chooseImage" size="32" color="#666"></u-icon>
						<view class="emoji-icon" @click="toggleEmojiPanel">😊</view>
					</view>
					<u-input type="text" v-model="messageText" placeholder="请输入消息..." confirm-type="send"
						@confirm="sendMessage" :focus="inputFocus" @focus="onInputFocus" @blur="onInputBlur" border="none" />
				</view>
				<view class="send-btn" :class="{ 'send-btn-active': messageText.trim() }" @click="sendMessage">
					<u-icon name="arrow-upward" color="#fff" size="28"></u-icon>
				</view>
			</view>
		</view>

		<!-- 表情面板 -->
		<view class="emoji-panel" v-if="showEmojiPanel">
			<scroll-view scroll-y="true" class="emoji-container">
				<view class="emoji-list">
					<view class="emoji-item" v-for="(emoji, index) in emojiList" :key="index"
						@click="insertEmoji(emoji)">
						<text>{{ emoji }}</text>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import { petApi } from '@/src/api/index.js';
import { api } from '@/src/api/index.js';

export default {
	data() {
		return {
			petId: null,
			petName: '',
			shopName: '萌宠AI助手',
			petInfo: null,
			messageText: '',
			messages: [],
			scrollTop: 0,
			showQuickReply: true,
			showEmojiPanel: false,
			inputFocus: false,
			quickReplies: [
				'狗狗饲养有什么注意事项？',
				'猫咪需要哪些日常用品？',
				'如何给宠物选择合适的食物？',
				'宠物生病的常见症状有哪些？',
				'如何训练我的新宠物？',
				'怎样给宠物洗澡和清洁？'
			],
			emojiList: [
				'😊', '😂', '😍', '🥰', '😘', '🤔', '😅',
				'👍', '👏', '🙏', '🐶', '🐱', '🐹', '🐰',
				'❤️', '💕', '💯', '🎉', '🌈', '🌸', '🍀'
			],
			sendBtnStyle: {
				backgroundColor: '#ff6600',
				color: '#fff',
				height: '70rpx',
				width: '120rpx',
				fontSize: '28rpx',
				border: 'none'
			},
			// 模拟数据
			mockPetInfo: {
				id: 1,
				title: '精品泰迪犬',
				price: 2499,
				image: '/static/pets/teddy1.jpg'
			},
			mockMessages: [
				{
					content: '您好！我是萌宠助手，您有任何关于宠物的问题都可以问我哦~',
					type: 'text',
					isSelf: false,
					avatar: '/static/ai-avatar.png',
					time: new Date(new Date().getTime() - 3600000),
					status: 'read'
				}
			],
			refreshing: false,
			// AI 相关
			conversationHistory: [], // 用于存储对话历史
			isAiTyping: false, // AI是否正在"输入"

			// 聊天历史记录相关
			userId: null, // 当前用户ID
			conversationId: null, // 当前会话ID
		}
	},
	onLoad(options) {
		// 获取用户ID
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo) {
			this.userId = userInfo.id;
		}

		if (options.petId) {
			this.petId = options.petId;
			if (options.petName) {
				this.petName = decodeURIComponent(options.petName);
			}
			this.loadPetInfo();
		}

		if (options.conversationId) {
			this.conversationId = options.conversationId;
			this.loadChatHistory();
		} else {
			// 否则创建新会话
			this.loadOrCreateConversation();
		}
	},
	methods: {
		// 返回到"我的"页面
		goToMyPage() {
			uni.navigateBack({
				delta: 1
			});
		},

		loadOrCreateConversation() {
			if (!this.userId) {
				this.createNewConversation();
				return;
			}
			// 尝试加载用户最近的会话
			api.chatApi.getConversations({ user_id: this.userId, page: 1, page_size: 1 })
				.then(res => {
					if (res.code === 200 && res.data && Array.isArray(res.data.records)) {
						const conversations = res.data.records;
						if (conversations.length > 0) {
							this.conversationId = conversations[0].id;
							this.loadChatHistory();
						} else {
							this.createNewConversation();
						}
					} else {
						this.createNewConversation();
					}
				})
				.catch(err => {
					console.error("无法获取会话，将创建新会话。", err);
					this.createNewConversation();
				});
		},

		// 创建新会话
		createNewConversation() {
			const welcomeMessage = {
				content: '您好！我是萌宠助手，您有任何关于宠物的问题都可以问我哦~',
				type: 'text',
				isSelf: false,
				avatar: '/static/ai-avatar.png', // 使用AI头像
				time: new Date(),
				status: 'read'
			};

			// 如果用户未登录，仅显示欢迎消息
			if (!this.userId) {
				this.messages = [welcomeMessage];
				this.$nextTick(() => {
					this.scrollToBottom();
				});
				return;
			}

			// 对于已登录用户，立即显示欢迎消息
			this.messages = [welcomeMessage];
			this.$nextTick(() => {
				this.scrollToBottom();
			});

			// 然后在后台创建会话并保存欢迎消息
			api.chatApi.createConversation({ userId: this.userId })
				.then(res => {
					console.log('创建会话返回数据:', res);

					if (res && res.code === 200 && res.data) {
						let conversationId = null;
						if (res.data && typeof res.data === 'object') {
							conversationId = res.data.id;
						} else if (typeof res.data === 'number') {
							conversationId = res.data;
						}

						if (conversationId) {
							this.conversationId = conversationId;
							console.log('设置会话ID成功:', this.conversationId);

							const welcomeMessageForDb = {
								conversationId: this.conversationId,
								userId: this.userId,
								role: 'assistant',
								content: welcomeMessage.content,
								contentType: 'text'
							};

							// 在后台保存欢迎消息
							api.chatApi.sendMessage(welcomeMessageForDb)
								.then(msgRes => {
									console.log('欢迎消息保存成功:', JSON.stringify(msgRes));
								})
								.catch(err => {
									console.error('保存欢迎消息失败:', err);
								});
						} else {
							console.error('无法获取会话ID');
						}
					} else {
						console.error('创建会话失败', res);
					}
				})
				.catch(err => {
					console.error('创建会话API调用失败:', err);
					if (err.response && err.response.status === 401) {
						uni.showToast({
							title: '登录已过期，请重新登录',
							icon: 'none'
						});
						this.userId = null;
						uni.removeStorageSync('userInfo');
					}
				});
		},

		// 加载聊天历史
		loadChatHistory() {
			if (!this.conversationId) {
				// 如果没有会话ID，则显示欢迎信息，而不是模拟消息
				this.createNewConversation();
				return;
			}

			// 调用API获取聊天历史
			api.chatApi.getMessages({
					conversation_id: this.conversationId
				})
				.then(res => {
					if (res && res.code === 200 && Array.isArray(res.data)) {
						// 转换消息格式
						const historyMessages = res.data.map(msg => ({
							content: msg.content,
							type: msg.content_type || 'text',
							isSelf: msg.role === 'user',
							avatar: msg.role === 'user' ? (uni.getStorageSync('userInfo')?.avatar || '/static/default-avatar.png.jpg') : '/static/ai-avatar.png',
							time: new Date(msg.created_at),
							status: 'read'
						}));

						// 如果历史记录为空，则添加欢迎语
						if (historyMessages.length === 0) {
							this.messages = [
								{
									content: '您好！我是萌宠助手，您有任何关于宠物的问题都可以问我哦~',
									type: 'text',
									isSelf: false,
									avatar: '/static/ai-avatar.png',
									time: new Date(),
									status: 'read'
								}
							];
						} else {
							this.messages = historyMessages;
						}
						
						// 重建对话历史
						this.rebuildConversationHistory();

						// 滚动到底部
						this.$nextTick(() => {
							this.scrollToBottom();
						});
					} else {
						// 加载失败也显示欢迎语
						this.createNewConversation();
					}
				})
				.catch(err => {
					console.error('获取聊天历史失败:', err);
					// 检查是否是401错误（令牌过期）
					if (err.response && err.response.status === 401) {
						console.warn('登录已过期，但仍可使用AI聊天功能');
						// 清除用户ID，使用游客模式
						this.userId = null;
						this.conversationId = null;
						uni.removeStorageSync('userInfo');
						uni.showToast({
							title: '您当前以游客身份聊天，无法加载历史消息',
							icon: 'none',
							duration: 3000
						});
					}
					// 即使加载失败，也显示欢迎消息
					this.createNewConversation();
				});
		},

		// 重建对话历史
		rebuildConversationHistory() {
			this.conversationHistory = [];

			// 确保对话历史是一一对应的
			const messages = [...this.messages];
			const cleanMessages = [];

			// 按照时间排序
			messages.sort((a, b) => a.time - b.time);

			// 确保用户和AI消息一一对应
			let expectSelf = true; // 期望下一条是用户消息

			for (let i = 0; i < messages.length; i++) {
				const msg = messages[i];

				// 如果角色符合预期，则添加到清理后的消息中
				if ((expectSelf && msg.isSelf) || (!expectSelf && !msg.isSelf)) {
					cleanMessages.push(msg);
					// 切换期望角色
					expectSelf = !expectSelf;
				}
				// 如果连续出现同一角色的消息，只保留最新的一条
				else if ((msg.isSelf && cleanMessages[cleanMessages.length - 1]?.isSelf) ||
					(!msg.isSelf && !cleanMessages[cleanMessages.length - 1]?.isSelf)) {
					// 替换最后一条消息
					cleanMessages[cleanMessages.length - 1] = msg;
				}
			}

			// 确保历史记录是成对的，如果最后一条是用户消息，则移除
			if (cleanMessages.length > 0 && cleanMessages[cleanMessages.length - 1].isSelf) {
				cleanMessages.pop();
			}

			// 最多取最近10对消息（20条）作为上下文
			const recentMessages = cleanMessages.slice(-20);

			recentMessages.forEach(msg => {
				this.conversationHistory.push({
					role: msg.isSelf ? 'user' : 'assistant',
					content: msg.content
				});
			});
		},

		// 发送消息
		sendMessage() {
			if (!this.messageText.trim()) {
				return;
			}

			// 添加消息到列表
			const newMessage = {
				content: this.messageText,
				type: 'text',
				isSelf: true,
				avatar: '/static/default-avatar.png.jpg',
				time: new Date(),
				status: 'sending' // 先标记为发送中
			};

			// 存储用户消息，用于AI对话历史
			const userMessage = {
				role: 'user',
				content: this.messageText
			};
			this.conversationHistory.push(userMessage);

			// 清空输入框和临时存储
			const messageToSend = this.messageText;
			this.messageText = '';

			// 隐藏快捷回复和表情面板
			this.showQuickReply = false;
			this.showEmojiPanel = false;

			// 添加消息到列表并滚动
			this.messages.push(newMessage);
			this.$nextTick(() => {
				this.scrollToBottom();
			});

			// 如果没有会话ID且用户已登录，需要先创建会话
			if (!this.conversationId && this.userId) {
				this.loadOrCreateConversation();
				// 在会话创建后的回调中会处理用户消息的保存
			}
			// 如果用户已登录且有会话ID，保存用户消息到数据库
			else if (this.userId && this.conversationId) {
				const msgData = {
					conversationId: this.conversationId,
					userId: this.userId,
					role: 'user',
					content: messageToSend,
					contentType: 'text'
				};

				api.chatApi.sendMessage(msgData)
					.then(() => {
						console.log('用户消息保存成功');
						// 更新消息状态为已读
						const index = this.messages.findIndex(msg => 
							msg.content === messageToSend && 
							msg.isSelf && 
							msg.status === 'sending'
						);
						if (index !== -1) {
							this.messages[index].status = 'read';
						}
					})
					.catch(err => {
						console.error('保存用户消息失败:', err);
						// 检查是否是401错误（令牌过期）
						if (err.response && err.response.status === 401) {
							uni.showToast({
								title: '登录已过期，请重新登录',
								icon: 'none'
							});
							this.userId = null;
						}
						
						// 更新消息状态为失败
						const index = this.messages.findIndex(msg => 
							msg.content === messageToSend && 
							msg.isSelf && 
							msg.status === 'sending'
						);
						if (index !== -1) {
							this.messages[index].status = 'failed';
						}
					});
			} else {
				// 游客模式，直接标记为已读
				const index = this.messages.findIndex(msg => 
					msg.content === messageToSend && 
					msg.isSelf && 
					msg.status === 'sending'
				);
				if (index !== -1) {
					this.messages[index].status = 'read';
				}
			}

			// 显示AI正在输入
			this.isAiTyping = true;

			// 发送消息给AI并获取回复
			this.sendAiMessage();
		},

		// 发送AI消息
		sendAiMessage() {
			// 如果没有对话历史或处于游客模式，直接使用DeepSeek API
			if (!this.conversationId || !this.userId) {
				this.isAiTyping = true;

				// 获取最后一条用户消息
				const lastUserMessage = this.conversationHistory[this.conversationHistory.length - 1];
				if (!lastUserMessage || lastUserMessage.role !== 'user') {
					console.error('无法找到有效的用户消息');
					this.isAiTyping = false;
					return;
				}

				// 准备对话历史，确保一一对应
				const history = this.conversationHistory.slice(0, -1);

				// 添加一个小延迟，模拟AI思考
				setTimeout(() => {
					api.aiApi.sendMessage(lastUserMessage.content, history)
						.then(res => {
							if (res && res.code === 200 && res.data) {
								const aiResponse = {
									content: res.data,
									type: 'text',
									isSelf: false,
									avatar: '/static/ai-avatar.png',
									time: new Date(),
									status: 'read'
								};

								// 添加AI回复到界面
								this.messages.push(aiResponse);

								// 存储AI回复，用于对话历史
								const aiMessage = {
									role: 'assistant',
									content: res.data
								};
								this.conversationHistory.push(aiMessage);

								this.$nextTick(() => {
									this.scrollToBottom();
									// 添加震动反馈
									uni.vibrateShort();
								});
							}
						})
						.catch(err => {
							console.error('AI回复错误:', err);
							// 添加错误消息
							this.messages.push({
								content: '抱歉，AI服务暂时不可用，请稍后再试。',
								type: 'text',
								isSelf: false,
								avatar: '/static/ai-avatar.png',
								time: new Date()
							});

							this.$nextTick(() => {
								this.scrollToBottom();
							});
						})
						.finally(() => {
							this.isAiTyping = false;
						});
				}, 1000); // 1秒延迟，让用户感知AI在思考
				return;
			}

			// 用户已登录且有会话ID的情况
			this.isAiTyping = true;

			// 获取最后一条用户消息
			const lastUserMessage = this.conversationHistory[this.conversationHistory.length - 1];
			if (!lastUserMessage || lastUserMessage.role !== 'user') {
				console.error('无法找到有效的用户消息');
				this.isAiTyping = false;
				return;
			}

			// 准备对话历史，确保一一对应
			const history = this.conversationHistory.slice(0, -1);

			// 添加一个小延迟，模拟AI思考
			setTimeout(() => {
				// 发送请求
				api.aiApi.sendMessage(lastUserMessage.content, history)
					.then(res => {
						if (res && res.code === 200 && res.data) {
							// 创建AI回复消息
							const aiResponse = {
								content: res.data,
								type: 'text',
								isSelf: false,
								avatar: '/static/ai-avatar.png',
								time: new Date(),
								status: 'read'
							};

							// 添加AI回复到界面
							this.messages.push(aiResponse);

							// 存储AI回复，用于对话历史
							const aiMessage = {
								role: 'assistant',
								content: res.data
							};
							this.conversationHistory.push(aiMessage);

							// 添加震动反馈
							uni.vibrateShort();

							// 保存到数据库
							return api.chatApi.sendMessage({
								conversationId: this.conversationId,
								userId: this.userId,
								role: 'assistant',
								content: res.data,
								contentType: 'text'
							});
						}
					})
					.catch(err => {
						console.error('AI回复错误:', err);

						// 添加错误消息
						this.messages.push({
							content: '抱歉，AI服务暂时不可用，请稍后再试。',
							type: 'text',
							isSelf: false,
							avatar: '/static/ai-avatar.png',
							time: new Date()
						});
					})
					.finally(() => {
						this.$nextTick(() => {
							this.scrollToBottom();
							this.isAiTyping = false;
						});
					});
			}, 1500); // 1.5秒延迟，让用户感知AI在思考
		},

		// 返回上一页 (u-navbar自带)
		goBack() {
			uni.navigateBack();
		},

		// 显示菜单
		showMenu() {
			uni.showActionSheet({
				itemList: ['清空聊天记录', '投诉商家', '加入收藏夹'],
				success: res => {
					switch (res.tapIndex) {
						case 0:
							this.clearChatHistory();
							break;
						case 1:
							this.reportShop();
							break;
						case 2:
							this.addToFavorite();
							break;
					}
				}
			});
		},

		// 清空聊天记录
		clearChatHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空聊天记录吗？',
				success: res => {
					if (res.confirm) {
						this.messages = [];
						uni.showToast({
							title: '聊天记录已清空',
							icon: 'success'
						});
					}
				}
			});
		},

		// 投诉商家
		reportShop() {
			uni.showToast({
				title: '投诉功能即将上线',
				icon: 'none'
			});
		},

		// 加入收藏夹
		addToFavorite() {
			uni.showToast({
				title: '已加入收藏夹',
				icon: 'success'
			});
		},

		// 加载宠物信息
		loadPetInfo() {
			// 显示加载中
			uni.showLoading({
				title: '加载中...'
			});

			// 调用API获取宠物详情
			petApi.getDetail(this.petId)
				.then(res => {
					if (res && res.code === 200 && res.data) {
						this.petInfo = res.data;
						if (this.petInfo.shop) {
							this.shopName = this.petInfo.shop.name;
						}
					} else {
						// 使用模拟数据
						this.petInfo = this.mockPetInfo;
						if (this.petName) {
							this.petInfo.title = this.petName;
						}
					}
				})
				.catch(err => {
					console.error('获取宠物详情失败:', err);
					// 使用模拟数据
					this.petInfo = this.mockPetInfo;
					if (this.petName) {
						this.petInfo.title = this.petName;
					}
				})
				.finally(() => {
					uni.hideLoading();
				});
		},

		// 选择图片
		chooseImage() {
			uni.chooseImage({
				count: 1,
				success: res => {
					const tempFilePath = res.tempFilePaths[0];

					// 添加图片消息
					const newMessage = {
						content: tempFilePath,
						type: 'image',
						isSelf: true,
						avatar: '/static/default-avatar.png.jpg',
						time: new Date(),
						status: 'sending'
					};

					this.messages.push(newMessage);

					// 隐藏快捷回复和表情面板
					this.showQuickReply = false;
					this.showEmojiPanel = false;

					// 滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom();
					});

					// 模拟上传成功
					setTimeout(() => {
						const index = this.messages.findIndex(msg => msg === newMessage);
						if (index !== -1) {
							this.messages[index].status = 'read';
							this.$forceUpdate();
						}
					}, 1000);
				}
			});
		},

		// 预览图片
		previewImage(url) {
			// 获取所有图片消息的URL
			const imageUrls = this.messages
				.filter(msg => msg.type === 'image')
				.map(msg => msg.content);

			uni.previewImage({
				urls: imageUrls,
				current: url
			});
		},

		// 切换表情面板
		toggleEmojiPanel() {
			this.showEmojiPanel = !this.showEmojiPanel;
			this.showQuickReply = false;
		},

		// 插入表情
		insertEmoji(emoji) {
			this.messageText += emoji;
		},

		// 输入框获取焦点
		onInputFocus() {
			this.inputFocus = true;
			this.showEmojiPanel = false;
		},

		// 输入框失去焦点
		onInputBlur() {
			this.inputFocus = false;
		},

		// 选择快捷回复
		selectQuickReply(item) {
			this.messageText = item;
			this.sendMessage();
		},

		// 关闭宠物卡片
		closePetCard() {
			this.petInfo = null;
		},

		// 滚动到底部
		scrollToBottom() {
			// 使用一个很大的值来滚动到底部
			this.scrollTop = 100000;
		},

		// 格式化日期
		formatDate(date) {
			if (!date) return '';

			const d = new Date(date);
			const now = new Date();
			const diff = now.getTime() - d.getTime();
			const day = 24 * 60 * 60 * 1000;

			// 今天
			if (diff < day && d.getDate() === now.getDate()) {
				return '今天';
			}

			// 昨天
			if (diff < 2 * day && d.getDate() === now.getDate() - 1) {
				return '昨天';
			}

			// 一周内
			if (diff < 7 * day) {
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				return weekdays[d.getDay()];
			}

			// 其他日期
			return `${d.getFullYear()}-${this.padZero(d.getMonth() + 1)}-${this.padZero(d.getDate())}`;
		},

		// 格式化时间
		formatTime(date) {
			if (!date) return '';

			const d = new Date(date);
			let hours = d.getHours();
			const minutes = d.getMinutes();

			// 12小时制
			const ampm = hours >= 12 ? '下午' : '上午';
			hours = hours % 12;
			hours = hours ? hours : 12; // 0点显示为12点

			return `${ampm} ${this.padZero(hours)}:${this.padZero(minutes)}`;
		},

		// 是否显示日期分割线
		shouldShowDate(prevTime, currTime) {
			if (!prevTime || !currTime) return false;

			const prev = new Date(prevTime);
			const curr = new Date(currTime);

			// 日期不同则显示分割线
			return prev.getDate() !== curr.getDate() ||
				prev.getMonth() !== curr.getMonth() ||
				prev.getFullYear() !== curr.getFullYear();
		},

		// 补零
		padZero(num) {
			return num < 10 ? `0${num}` : num;
		},

		// 格式化 AI 回复内容
		formatMessage(content) {
			if (!content) return '';

			// 处理换行
			let formatted = content.replace(/\n/g, '<br>');

			// 处理粗体文本 **text**
			formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

			// 处理斜体文本 *text*
			formatted = formatted.replace(/\*([^*]+)\*/g, '<em>$1</em>');

			// 处理列表项
			formatted = formatted.replace(/^- (.*?)$/gm, '• $1<br>');
			formatted = formatted.replace(/^\d+\. (.*?)$/gm, '$&<br>');

			// 处理标题
			formatted = formatted.replace(/^### (.*?)$/gm, '<h3 style="font-size: 32rpx; margin: 10rpx 0;">$1</h3>');
			formatted = formatted.replace(/^## (.*?)$/gm, '<h2 style="font-size: 34rpx; margin: 10rpx 0;">$1</h2>');
			formatted = formatted.replace(/^# (.*?)$/gm, '<h1 style="font-size: 36rpx; margin: 10rpx 0;">$1</h1>');

			return formatted;
		},

		// 处理AI错误的方法
		handleAiError() {
			// 移除临时"正在思考"消息
			this.messages = this.messages.filter(msg => !msg.isTemp);

			// 添加错误消息
			this.messages.push({
				content: '抱歉，我遇到了一点小问题，请稍后再试或联系人工客服。',
				type: 'text',
				isSelf: false,
				avatar: '/static/default-avatar.png.jpg',
				time: new Date(),
				status: 'read'
			});

			this.$nextTick(() => {
				this.scrollToBottom();
			});
		}
	}
}
</script>

<style lang="scss">
.consult-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f7f8fa;
	font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;

	.nav-right {
		margin-right: 20rpx;
	}

	.pet-card {
		display: flex;
		align-items: center;
		padding: 24rpx;
		background-color: #fff;
		margin: 20rpx;
		border-radius: 16rpx;
		position: relative;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

		.pet-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 12rpx;
			margin-right: 24rpx;
		}

		.pet-info {
			flex: 1;

			.pet-name {
				font-size: 30rpx;
				color: #333;
				margin-bottom: 12rpx;
				display: block;
				font-weight: 500;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 400rpx;
			}

			.pet-price {
				font-size: 32rpx;
				color: #ff6600;
				font-weight: bold;
			}
		}

		.pet-card-close {
			position: absolute;
			top: 16rpx;
			right: 16rpx;
			width: 40rpx;
			height: 40rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.chat-wrapper {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.chat-container {
		flex: 1;
		padding: 24rpx;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;

		.message-date {
			text-align: center;
			margin: 30rpx 0;

			text {
				font-size: 24rpx;
				color: #999;
				background-color: rgba(0, 0, 0, 0.05);
				padding: 8rpx 20rpx;
				border-radius: 30rpx;
			}
		}

		.message-list {
			.message-item {
				display: flex;
				margin-bottom: 32rpx;
				animation: fadeIn 0.3s ease-in-out;
				margin-left: 0rpx; /* 左侧消息与右侧保持一致的边距 */
				margin-right: 0rpx; /* 确保两侧边距一致 */

				/deep/ .u-avatar {
					flex-shrink: 0;
					border: 1px solid rgba(0, 0, 0, 0.05);
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
				}
				
				.message-wrapper {
					margin: 0 16rpx;
					max-width: 70%;
					display: flex;
					flex-direction: column;

					.message-name {
						margin-bottom: 6rpx;

						text {
							font-size: 24rpx;
							color: #999;
						}
					}

					.message-content {
						background-color: #fff;
						border-radius: 18rpx 18rpx 18rpx 4rpx;
						padding: 20rpx;
						position: relative;
						align-self: flex-start;
						box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
						transition: transform 0.2s ease;
						margin-bottom: 8rpx; /* 为底部状态和时间留出空间 */

						.message-text {
							font-size: 28rpx;
							color: #333;
							line-height: 1.6;
							word-break: break-word;

							/deep/ strong {
								font-weight: bold;
							}

							/deep/ em {
								font-style: italic;
							}

							/deep/ h1,
							/deep/ h2,
							/deep/ h3 {
								margin: 10rpx 0;
								font-weight: bold;
							}

							/deep/ br {
								display: block;
								margin: 5rpx 0;
							}
						}

						.message-image {
							border-radius: 12rpx;
							box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
							transition: transform 0.2s ease;
							
							&:active {
								transform: scale(0.98);
							}
						}

						&.image-message {
							padding: 8rpx;
							background-color: transparent;
							box-shadow: none;
						}
					}

					.message-footer {
						display: flex;
						align-items: center;
						margin-top: 4rpx;
						font-size: 22rpx;
						color: #999;
						
						.message-status {
							margin-right: 6rpx;
						}
						
						.status-read {
							color: #52c41a;
							margin-right: 8rpx;
							font-size: 22rpx;
						}
						
						.message-time {
							font-size: 22rpx;
							color: #999;
						}
					}
				}

				&.message-self {
					flex-direction: row-reverse;
					margin-right: 40rpx; /* 用户消息整体向左移动 */
					margin-left: 0rpx; /* 左侧留出更多空间 */
					
					/deep/ .u-avatar {
						margin-left: 8rpx; /* 确保右侧头像不被覆盖 */
					}
					
					.message-wrapper {
						align-items: flex-end;

						.message-content {
							background: linear-gradient(135deg, #ff9966, #ff6600); /* 恢复渐变背景 */
							border-radius: 18rpx 18rpx 4rpx 18rpx;
							color: #fff;
							align-self: flex-end;
							border: none;

							.message-text {
								color: #fff; /* 确保文字颜色为白色，与背景对比 */
							}
						}

						.message-time {
							align-self: flex-end;
						}
					}
				}
			}
		}

		.typing-indicator {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 20rpx 0;
			
			.typing-dots {
				display: flex;
				align-items: center;
				margin-right: 10rpx;
				
				.dot {
					display: inline-block;
					width: 12rpx;
					height: 12rpx;
					background-color: #ff6600;
					border-radius: 50%;
					margin: 0 4rpx;
					opacity: 0.6;
					
					&:nth-child(1) {
						animation: blink 1s infinite 0s;
					}
					
					&:nth-child(2) {
						animation: blink 1s infinite 0.2s;
					}
					
					&:nth-child(3) {
						animation: blink 1s infinite 0.4s;
					}
				}
			}
			
			text {
				font-size: 26rpx;
				color: #666;
			}
		}

		.system-message {
			text-align: center;
			margin: 30rpx 0;

			text {
				font-size: 26rpx;
				color: #ff6600;
				background-color: #fff5e1;
				padding: 12rpx 24rpx;
				border-radius: 30rpx;
				box-shadow: 0 2rpx 6rpx rgba(255, 102, 0, 0.1);
			}
		}
	}

	.quick-reply-container {
		padding: 16rpx 24rpx;
		background-color: #fff;
		border-top: 1rpx solid #f0f0f0;

		.quick-reply-scroll {
			width: 100%;
			white-space: nowrap;
		}

		.quick-reply-list {
			display: flex;
			gap: 16rpx;
			padding: 4rpx 0;

			.quick-reply-item {
				padding: 12rpx 24rpx;
				background-color: #f8f8f8;
				color: #666;
				font-size: 26rpx;
				border-radius: 30rpx;
				display: inline-block;
				white-space: nowrap;
				transition: all 0.2s ease;
				
				&:active {
					background-color: #fff5e1;
					color: #ff6600;
					transform: scale(0.98);
				}
			}
		}
	}

	.input-area {
		background-color: #fff;
		padding: 16rpx 24rpx;
		border-top: 1rpx solid #f0f0f0;
		position: relative;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.03);
		
		.input-wrapper {
			display: flex;
			align-items: center;
			
			.input-box {
				flex: 1;
				background-color: #f8f8f8;
				border-radius: 36rpx;
				padding: 0 20rpx;
				margin-right: 16rpx;
				box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
				height: 72rpx;
				display: flex;
				align-items: center;
				
				.input-tools {
					display: flex;
					align-items: center;
					margin-right: 10rpx;
					
					.tool-icon {
						margin-right: 16rpx;
						padding: 6rpx;
						transition: all 0.2s ease;
						
						&:active {
							transform: scale(0.9);
							background-color: rgba(0,0,0,0.05);
							border-radius: 50%;
						}
					}
					
					.emoji-icon {
						font-size: 32rpx;
						line-height: 1;
						padding: 6rpx;
						margin-right: 16rpx;
						transition: all 0.2s ease;
						
						&:active {
							transform: scale(0.9);
							background-color: rgba(0,0,0,0.05);
							border-radius: 50%;
						}
					}
				}
	
				.u-input {
					flex: 1;
				}
			}
	
			.send-btn {
				width: 72rpx;
				height: 72rpx;
				border-radius: 50%;
				background-color: #ddd;
				display: flex;
				justify-content: center;
				align-items: center;
				transition: all 0.3s ease;
				
				&-active {
					background-color: #ff6600;
					box-shadow: 0 4rpx 12rpx rgba(255, 102, 0, 0.3);
					
					&:active {
						transform: scale(0.95);
						box-shadow: 0 2rpx 6rpx rgba(255, 102, 0, 0.2);
					}
				}
			}
		}
	}

	.emoji-panel {
		height: 400rpx;
		background-color: #fff;
		border-top: 1rpx solid #f0f0f0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.emoji-container {
			height: 100%;
		}

		.emoji-list {
			display: flex;
			flex-wrap: wrap;
			padding: 20rpx;

			.emoji-item {
				width: 80rpx;
				height: 80rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				transition: transform 0.2s ease;
				
				&:active {
					transform: scale(0.9);
					background-color: #f8f8f8;
					border-radius: 12rpx;
				}

				text {
					font-size: 40rpx;
				}
			}
		}
	}
}

@keyframes blink {
	0% { opacity: 0.4; }
	50% { opacity: 1; }
	100% { opacity: 0.4; }
}

@keyframes fadeIn {
	from { opacity: 0; transform: translateY(10rpx); }
	to { opacity: 1; transform: translateY(0); }
}
</style>